﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace PicStore.Common.Exceptions
{
    public class ExceptionWrapper
    {
        static bool _isWebApp
        {
            get
            {
                return HttpContext.Current != null;
            }
        }

        public static void WrapMessage(ref string errorMsg, Exception exception)
        {
            if (string.IsNullOrEmpty(errorMsg) && _isWebApp)
            {
                errorMsg = String.Format("<div style='line-height:150%'><b>URL</b>: {0}</div>", HttpContext.Current.Request.RawUrl);
                errorMsg += String.Format("<div style='line-height:150%'><b>Client IP</b>: {0}</div>", HttpContext.Current.Request.UserHostAddress);

                errorMsg += String.Format("<div style='line-height:150%'><b>Ticket</b>: {0}</div>", (HttpContext.Current.Request.IsAuthenticated ? HttpContext.Current.User.Identity.Name : "GUEST"));
            }

            if (exception == null)
                return;

            errorMsg += !_isWebApp ? "Exception\n" : "<div style='line-height:150%'><b><font color='red'>Exception</font></b></div>";

            errorMsg += String.Format(!_isWebApp ? "Message: {0}\n" : "<div style='line-height:150%'><b>Message</b>: {0}</div>", exception.GetBaseException().Message);
            errorMsg += String.Format(!_isWebApp ? "Type: {0}\n" : "<div style='line-height:150%'><b>Type</b>: {0}</div>", exception.GetBaseException().GetType().FullName);
            errorMsg += String.Format(!_isWebApp ? "Source: {0}\n" : "<div style='line-height:150%'><b>Source</b>: {0}</div>", exception.GetBaseException().Source);
            errorMsg += !_isWebApp ? "StackTrace:\n" : "<div style='line-height:150%'><b>StackTrace</b>:";

            string stackTrace = exception.StackTrace;
            if (!stackTrace.EndsWith(Environment.NewLine))
                stackTrace += Environment.NewLine;

            if (_isWebApp)
            {
                stackTrace = (Environment.NewLine + stackTrace)
                    .Replace(Environment.NewLine, "</li><li>")
                    .Substring(5);
            }
            else
            {
                stackTrace = stackTrace.Replace(Environment.NewLine, "\n");
            }

            stackTrace = stackTrace.Substring(0, stackTrace.Length - 4);

            errorMsg += string.Format(!_isWebApp ? "{0}\n" : "<ul>{0}</ul><div>", stackTrace);

            if (exception.InnerException != null)
            {
                WrapMessage(ref errorMsg, exception.InnerException);
            }
        }
    }
}
